package com.epmis.epmis.Service.impl;

import com.epmis.epmis.Mapper.LoginMapper;
import com.epmis.epmis.Service.LoginService;
import com.epmis.epmis.pojo.Enterprise;
import com.epmis.epmis.pojo.Post;
import com.epmis.epmis.pojo.User;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class LoginServiceImpl implements LoginService {
    @Resource
    LoginMapper loginMapper;

    public int Login(String username,String password) {
        User result = loginMapper.Login(username);
        if(result == null) {
            return 0;
        }else if(!result.getPassword().equals(password)){
            return 1;
        }else if(result.getStatus() == 1){
            return 2;
        }else{
            return 3;
        }
    }

    public User getUserMessage(String username) {
        return loginMapper.getUserMessage(username);
    }

    public int Register(User user,String enterpriseName){
        Enterprise enterprise = loginMapper.findEnterprise(enterpriseName);
        if(enterprise != null){
            return 0;
        }
        User findPhone = loginMapper.findPhone(user.getPhone());
        if(findPhone != null){
            return 1;
        }
        User findEmail = loginMapper.findEmail(user.getEmail());
        if(findEmail != null){
            return 2;
        }
        int insertEnterprise = loginMapper.insertEnterprise(enterpriseName);
        if(insertEnterprise == 0){
            return 3;
        }
        Enterprise GetEnterpriseId = loginMapper.getEnterpriseId(enterpriseName);


        int enterpriseId = GetEnterpriseId.getId();
        loginMapper.insertHighPost(enterpriseId);
        loginMapper.insertManagerPost(enterpriseId);

        Post post = loginMapper.getPostId(enterpriseId);
        user.setPost_id(post.getId());
        user.setEnterprise_id(enterpriseId);

        int insertMember = loginMapper.insertMember(user);
        if(insertMember == 0){
            return 3;
        }

        User getOriginatorId = loginMapper.getOriginatorId(user.getPhone());
        int originatorId = getOriginatorId.getId();

        int updateOriginatorId = loginMapper.updateOriginatorId(enterpriseId,originatorId);
        if(updateOriginatorId == 0){
            return 3;
        }
        return 4;
    }

    public int updatePassword(String password,String phone){
        User havePhone = loginMapper.havePhone(phone);
        if(havePhone == null){
            return 0;
        }

        loginMapper.updatePassword(password,phone);
        return 1;
    }

    public int updatePasswordE(String password,String email){
        User haveEmail = loginMapper.haveEmail(email);
        if(haveEmail == null){
            return 0;
        }
        loginMapper.updatePasswordE(password,email);
        return 1;
    }
}
